"use client"

import { useState } from "react"
import { Button } from "@/components/ui/button"
import { Input } from "@/components/ui/input"
import { Badge } from "@/components/ui/badge"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from "@/components/ui/select"
import {
  Search,
  Filter,
  Plus,
  Zap,
  User,
  Calendar,
  Activity,
  CheckCircle,
  Clock,
  AlertTriangle,
  Settings
} from "lucide-react"

interface MotorProject {
  id: string
  name: string
  customer: string
  salesperson: string
  requirements: string
  status: string
  motorType: string
  motorPower: string
  motorVoltage: string
  motorCurrent: string
  ratedSpeed: string
  ratedTorque: string
  createTime: string
  updateTime: string
  progress: number
}

interface MotorProjectListProps {
  onSelectProject?: (projectId: string) => void
  onCreateProject?: () => void
}

export function MotorProjectList({ onSelectProject, onCreateProject }: MotorProjectListProps) {
  const [projects, setProjects] = useState<MotorProject[]>([])
  const [loading, setLoading] = useState(true)
  const [searchTerm, setSearchTerm] = useState("")
  const [statusFilter, setStatusFilter] = useState("all")
  const [motorTypeFilter, setMotorTypeFilter] = useState("all")

  // 模拟项目数据
  const mockProjects: MotorProject[] = [
    {
      id: "1",
      name: "SZCG - 18",
      customer: "苏州成就智能科技有限公司",
      salesperson: "陈涛",
      requirements: "45电机55风道22.2V250W PWM驱动",
      status: "active",
      motorType: "无刷电机",
      motorPower: "250W",
      motorVoltage: "22.2V",
      motorCurrent: "10A",
      ratedSpeed: "3000rpm",
      ratedTorque: "5.0Nm",
      createTime: "2024-01-10",
      updateTime: "2024-01-15",
      progress: 75
    },
    {
      id: "2",
      name: "工业风扇控制",
      customer: "深圳电子科技",
      salesperson: "李明",
      requirements: "大功率工业风扇控制系统",
      status: "testing",
      motorType: "步进电机",
      motorPower: "1500W",
      motorVoltage: "48V",
      motorCurrent: "30A",
      ratedSpeed: "1500rpm",
      ratedTorque: "10.0Nm",
      createTime: "2024-01-08",
      updateTime: "2024-01-14",
      progress: 45
    },
    {
      id: "3",
      name: "伺服驱动系统",
      customer: "上海自动化设备",
      salesperson: "王芳",
      requirements: "高精度伺服驱动控制系统",
      status: "completed",
      motorType: "伺服电机",
      motorPower: "3000W",
      motorVoltage: "380V",
      motorCurrent: "50A",
      ratedSpeed: "6000rpm",
      ratedTorque: "15.0Nm",
      createTime: "2024-01-05",
      updateTime: "2024-01-10",
      progress: 100
    },
    {
      id: "4",
      name: "智能家居电机",
      customer: "广州智能家居",
      salesperson: "张伟",
      requirements: "低功耗智能家居电机控制",
      status: "pending",
      motorType: "有刷电机",
      motorPower: "100W",
      motorVoltage: "12V",
      motorCurrent: "5A",
      ratedSpeed: "2000rpm",
      ratedTorque: "2.0Nm",
      createTime: "2024-01-12",
      updateTime: "2024-01-12",
      progress: 10
    }
  ]

  useState(() => {
    // 模拟API调用
    const fetchProjects = async () => {
      try {
        setLoading(true)
        const response = await fetch('/api/motor-projects')
        if (response.ok) {
          const data = await response.json()
          setProjects(data)
        }
      } catch (error) {
        console.error('Error fetching projects:', error)
        // 如果API失败，使用模拟数据
        setProjects(mockProjects)
      } finally {
        setLoading(false)
      }
    }
    
    fetchProjects()
  })

  const getStatusColor = (status: string) => {
    switch (status) {
      case "active": return "bg-green-100 text-green-800"
      case "testing": return "bg-yellow-100 text-yellow-800"
      case "completed": return "bg-blue-100 text-blue-800"
      case "pending": return "bg-gray-100 text-gray-800"
      default: return "bg-gray-100 text-gray-800"
    }
  }

  const getStatusIcon = (status: string) => {
    switch (status) {
      case "active": return <Activity className="h-4 w-4" />
      case "testing": return <Clock className="h-4 w-4" />
      case "completed": return <CheckCircle className="h-4 w-4" />
      case "pending": return <AlertTriangle className="h-4 w-4" />
      default: return <AlertTriangle className="h-4 w-4" />
    }
  }

  const getStatusText = (status: string) => {
    switch (status) {
      case "active": return "进行中"
      case "testing": return "测试中"
      case "completed": return "已完成"
      case "pending": return "待开始"
      default: return "未知"
    }
  }

  const filteredProjects = projects.filter(project => {
    const matchesSearch = searchTerm === "" || 
      project.name.toLowerCase().includes(searchTerm.toLowerCase()) ||
      project.customer.toLowerCase().includes(searchTerm.toLowerCase()) ||
      project.requirements.toLowerCase().includes(searchTerm.toLowerCase()) ||
      project.motorType.toLowerCase().includes(searchTerm.toLowerCase())

    const matchesStatus = statusFilter === "all" || project.status === statusFilter
    const matchesMotorType = motorTypeFilter === "all" || project.motorType === motorTypeFilter

    return matchesSearch && matchesStatus && matchesMotorType
  })

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="text-center">
          <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600 mx-auto"></div>
          <p className="mt-2 text-sm text-gray-500">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="space-y-6">
      {/* 顶部工具栏 */}
      <div className="flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between">
        <div>
          <h1 className="text-2xl font-bold">电机控制项目</h1>
          <p className="text-gray-600">管理和监控所有电机控制项目</p>
        </div>
        
        <Button onClick={onCreateProject} className="flex items-center gap-2">
          <Plus className="h-4 w-4" />
          创建新项目
        </Button>
      </div>

      {/* 统计卡片 */}
      <div className="grid grid-cols-1 md:grid-cols-4 gap-4">
        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">总项目数</p>
                <p className="text-2xl font-bold">{projects.length}</p>
              </div>
              <Settings className="h-8 w-8 text-blue-600" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">进行中</p>
                <p className="text-2xl font-bold">{projects.filter(p => p.status === 'active').length}</p>
              </div>
              <Activity className="h-8 w-8 text-green-600" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">测试中</p>
                <p className="text-2xl font-bold">{projects.filter(p => p.status === 'testing').length}</p>
              </div>
              <Clock className="h-8 w-8 text-yellow-600" />
            </div>
          </CardContent>
        </Card>

        <Card>
          <CardContent className="p-4">
            <div className="flex items-center justify-between">
              <div>
                <p className="text-sm font-medium text-gray-600">已完成</p>
                <p className="text-2xl font-bold">{projects.filter(p => p.status === 'completed').length}</p>
              </div>
              <CheckCircle className="h-8 w-8 text-purple-600" />
            </div>
          </CardContent>
        </Card>
      </div>

      {/* 搜索和筛选 */}
      <Card>
        <CardContent className="p-4">
          <div className="flex flex-col lg:flex-row gap-4">
            <div className="relative flex-1">
              <Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-gray-400" />
              <Input
                placeholder="搜索项目名称、客户、需求或电机类型..."
                value={searchTerm}
                onChange={(e) => setSearchTerm(e.target.value)}
                className="pl-10"
              />
            </div>
            
            <div className="flex gap-2">
              <Select value={statusFilter} onValueChange={setStatusFilter}>
                <SelectTrigger className="w-32">
                  <SelectValue placeholder="状态" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部状态</SelectItem>
                  <SelectItem value="active">进行中</SelectItem>
                  <SelectItem value="testing">测试中</SelectItem>
                  <SelectItem value="completed">已完成</SelectItem>
                  <SelectItem value="pending">待开始</SelectItem>
                </SelectContent>
              </Select>
              
              <Select value={motorTypeFilter} onValueChange={setMotorTypeFilter}>
                <SelectTrigger className="w-32">
                  <SelectValue placeholder="电机类型" />
                </SelectTrigger>
                <SelectContent>
                  <SelectItem value="all">全部类型</SelectItem>
                  <SelectItem value="无刷电机">无刷电机</SelectItem>
                  <SelectItem value="有刷电机">有刷电机</SelectItem>
                  <SelectItem value="步进电机">步进电机</SelectItem>
                  <SelectItem value="伺服电机">伺服电机</SelectItem>
                </SelectContent>
              </Select>
            </div>
          </div>
        </CardContent>
      </Card>

      {/* 项目列表 */}
      <div className="grid grid-cols-1 lg:grid-cols-2 xl:grid-cols-3 gap-6">
        {filteredProjects.map((project) => (
          <Card key={project.id} className="hover:shadow-lg transition-shadow cursor-pointer" onClick={() => onSelectProject?.(project.id)}>
            <CardHeader className="pb-3">
              <div className="flex items-start justify-between">
                <div className="flex-1">
                  <CardTitle className="text-lg">{project.name}</CardTitle>
                  <p className="text-sm text-gray-500 mt-1">{project.customer}</p>
                </div>
                <Badge className={getStatusColor(project.status)}>
                  {getStatusIcon(project.status)}
                  <span className="ml-1">{getStatusText(project.status)}</span>
                </Badge>
              </div>
            </CardHeader>
            
            <CardContent className="space-y-4">
              {/* 需求描述 */}
              <div>
                <p className="text-sm text-gray-600 line-clamp-2">{project.requirements}</p>
              </div>
              
              {/* 电机参数 */}
              <div className="grid grid-cols-2 gap-2 text-sm">
                <div className="flex items-center gap-1">
                  <Zap className="h-3 w-3 text-blue-600" />
                  <span className="text-gray-600">类型:</span>
                  <span className="font-medium">{project.motorType}</span>
                </div>
                <div className="flex items-center gap-1">
                  <Zap className="h-3 w-3 text-green-600" />
                  <span className="text-gray-600">功率:</span>
                  <span className="font-medium">{project.motorPower}</span>
                </div>
                <div className="flex items-center gap-1">
                  <Zap className="h-3 w-3 text-yellow-600" />
                  <span className="text-gray-600">电压:</span>
                  <span className="font-medium">{project.motorVoltage}</span>
                </div>
                <div className="flex items-center gap-1">
                  <Zap className="h-3 w-3 text-red-600" />
                  <span className="text-gray-600">电流:</span>
                  <span className="font-medium">{project.motorCurrent}</span>
                </div>
              </div>
              
              {/* 进度条 */}
              <div>
                <div className="flex justify-between items-center mb-1">
                  <span className="text-sm text-gray-600">项目进度</span>
                  <span className="text-sm font-medium">{project.progress}%</span>
                </div>
                <div className="w-full h-2 bg-gray-200 rounded-full overflow-hidden">
                  <div 
                    className={`h-full rounded-full ${
                      project.progress === 100 ? 'bg-green-500' : 
                      project.progress > 50 ? 'bg-blue-500' : 'bg-yellow-500'
                    }`}
                    style={{ width: `${project.progress}%` }}
                  />
                </div>
              </div>
              
              {/* 底部信息 */}
              <div className="flex justify-between items-center pt-2 border-t">
                <div className="flex items-center gap-2 text-sm text-gray-500">
                  <User className="h-3 w-3" />
                  <span>{project.salesperson}</span>
                </div>
                <div className="flex items-center gap-2 text-sm text-gray-500">
                  <Calendar className="h-3 w-3" />
                  <span>{new Date(project.updateTime).toLocaleDateString()}</span>
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {filteredProjects.length === 0 && (
        <div className="text-center py-12">
          <div className="text-gray-400 mb-4">
            <Search className="h-12 w-12 mx-auto" />
          </div>
          <h3 className="text-lg font-medium text-gray-900 mb-2">
            没有找到项目
          </h3>
          <p className="text-gray-500 mb-4">
            尝试调整搜索条件或创建新项目
          </p>
          <Button onClick={onCreateProject}>
            <Plus className="h-4 w-4 mr-2" />
            创建新项目
          </Button>
        </div>
      )}
    </div>
  )
}